<template>
  <div class="billing-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>对账单管理系统</h1>
      <div v-if="isLoggedIn" class="user-info">
        <span>欢迎，({{ userInfo.username !== 'admin' ? '供应商' : '运营人员' }})</span>
        <el-button type="primary" size="small" @click="handleLogout" style="margin-left: 10px;">登出</el-button>
      </div>
    </div>

    <!-- 供应商视图 -->
    <div v-if="userType === 'supplier'">
      <supplier-billing-management></supplier-billing-management>
    </div>

    <!-- 运营商视图 -->
    <div v-else-if="userType === 'yunying'">
      <yunying-billing-management></yunying-billing-management>
    </div>

    <!-- 未登录或未知用户类型 -->
    <div v-else>
      <el-card shadow="hover">
        <div class="no-access">
          <el-alert title="请先登录" type="warning" show-icon></el-alert>
          <el-button type="primary" @click="handleLogin">前往登录</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入供应商和运营商对账单组件
import SupplierBillingManagement from './SupplierBillingManagement.vue'
import YunyingBillingManagement from './YunyingBillingManagement.vue'
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'BillingManagement',
  components: {
    SupplierBillingManagement,
    YunyingBillingManagement
  },
  computed: {
    ...mapGetters(['userInfo', 'userType', 'isLoggedIn'])
  },
  created() {
    // 检查用户是否登录
    this.checkLoginStatus()
  },
  methods: {
    ...mapActions(['fetchUserInfo', 'logout']),
    checkLoginStatus() {
      if (this.isLoggedIn) {
        // 如果已登录，获取用户信息
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        this.fetchUserInfo(userInfo.id)
          .catch(error => {
            console.error('获取用户信息失败:', error)
            this.handleLogin()
          })
      } else {
        this.handleLogin()
      }
    },
    handleLogin() {
      this.$router.push('/login')
    },
    handleLogout() {
      this.logout()
      this.$router.push('/login')
    }
  },
  watch: {
    // 监听用户类型变化
    userType(newValue) {
      // 可以在这里添加用户类型变化后的逻辑
      console.log('用户类型已变更为:', newValue)
    }
  }
}
</script>

<style scoped>
.billing-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.user-info {
  display: flex;
  align-items: center;
}

.no-access {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.no-access .el-button {
  margin-top: 20px;
}
</style>